package com.atguigu.tingshu.user.service.impl;
import java.util.Date;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.WxMaUserService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.album.client.AlbumInfoFeignClient;
import com.atguigu.tingshu.common.constant.PublicConstant;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.minio.service.FileOpsService;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.common.util.MongoUtil;
import com.atguigu.tingshu.model.user.*;
import com.atguigu.tingshu.user.mapper.UserInfoMapper;
import com.atguigu.tingshu.user.mapper.UserPaidAlbumMapper;
import com.atguigu.tingshu.user.mapper.UserPaidTrackMapper;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.user.service.VipServiceConfigService;
import com.atguigu.tingshu.vo.album.TrackListVo;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.atguigu.tingshu.vo.user.UserCollectVo;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.bson.types.ObjectId;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.RsaVerifier;
import org.springframework.security.jwt.crypto.sign.Signer;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private WxMaService wxMaService;
    @Autowired
    private Signer rsaSigner;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RabbitService rabbitService;
    @Autowired
    private FileOpsService fileOpsServiceImpl;
    @Autowired
    private UserPaidTrackMapper userPaidTrackMapper;
    @Autowired
    private UserPaidAlbumMapper userPaidAlbumMapper;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Qualifier("com.atguigu.tingshu.album.client.AlbumInfoFeignClient")
    @Autowired
    private AlbumInfoFeignClient albumInfoFeignClient;
    @Autowired
    private VipServiceConfigService vipServiceConfigService;
    //验证用户登录,返回token
    @Override
    public Map<String, Object> wxLogin(String code) {
        //验证code码是否存在
        if (!StringUtils.hasText(code)) {
            throw new GuiguException(201, "code码不存在，登录失败");
        }

        //code码存在,获取微信登录的客服端
        String openId = "";
        WxMaUserService userService = wxMaService.getUserService();

        try {
            WxMaJscode2SessionResult sessionInfo = userService.getSessionInfo(code);
            //获取用户身份唯一标识
            openId = sessionInfo.getOpenid();
            if (!StringUtils.hasText(openId)) {
                throw new GuiguException(201, "微信内部处理异常，登录失败");
            }
        } catch (WxErrorException e) {
            throw new GuiguException(201, "微信内部处理异常，登录失败");
        }

        //优化缓存
        String refreshTokenKey = RedisConstant.USER_LOGIN_KEY_PREFIX + "refresh" + openId;
        String refreshToken = redisTemplate.opsForValue().get(refreshTokenKey);
        if (StringUtils.hasText(refreshToken)) {
            return getStringObjectHashMap(openId, refreshToken, refreshTokenKey);
        }

        //数据库查询用户是否存在
        LambdaQueryWrapper<UserInfo> infoLambdaQueryWrapper =
                new LambdaQueryWrapper<UserInfo>()
                        .eq(UserInfo::getWxOpenId, openId);
        UserInfo userInfo = userInfoMapper.selectOne(infoLambdaQueryWrapper);
        if (userInfo == null) {
            //用户不存在进行注册
            userInfo = new UserInfo();
            userInfo.setWxOpenId(openId);
            userInfo.setNickname("昵称-hzk-【" + System.currentTimeMillis() + "】");
            userInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg"); //初始化一个用户的头像
            userInfo.setIsVip(0);
            userInfo.setVipExpireTime(new Date());
            userInfo.setGender(0);
            userInfo.setIntro("简介");
            int insert = userInfoMapper.insert(userInfo);
            log.info("注册用户信息：{}", insert > 0 ? "success" : "fail");
            // TODO 对用户账户进行初始化(消息中间件异步进行)
            rabbitService.sendMessage(MqConst.EXCHANGE_ACCOUNT, MqConst.ROUTING_USER_REGISTER, userInfo.getId().toString());
        }
        //获取jsonWebToken
        String jsonWebToken = getJsonWebToken(openId, userInfo.getId());

        //存到redis中
        return getStringObjectHashMap(openId, jsonWebToken, refreshTokenKey);
    }

    //存到redis中并获取返回map对象
    @NotNull
    private HashMap<String, Object> getStringObjectHashMap(String openId, String jsonWebToken, String refreshTokenKey) {
        String accessTokenKey = RedisConstant.USER_LOGIN_KEY_PREFIX + "access" + openId;
        redisTemplate.opsForValue().set(accessTokenKey, jsonWebToken, 30, TimeUnit.DAYS);
        redisTemplate.opsForValue().set(refreshTokenKey, jsonWebToken, 30, TimeUnit.DAYS);

        //将自定义结果返回给前端
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("token", jsonWebToken);
        hashMap.put("refreshToken", jsonWebToken);
        return hashMap;
    }


    //获取jsonWebToken
    private String getJsonWebToken(String openId, Long userId) {
        //自定义登录信息(前端需要的用户身份唯一标识(JWT:token))
        JSONObject payloadMap = new JSONObject();
        payloadMap.put("openId", openId);
        payloadMap.put("userId", userId);

        //使用封装的JWT得到JWT对象
        Jwt jwt = JwtHelper.encode(payloadMap.toString(), rsaSigner);
        //获得Jwt对象的token
        return jwt.getEncoded();
    }

    //刷新token
    @Override
    public Map<String, Object> refresh() {
        //获取请求对象,从其中获取openId
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        //从请求对象中获取token,验签并解析负载数据
        String token = requestAttributes.getRequest().getHeader("token");
        Jwt jwt = JwtHelper.decodeAndVerify(token, new RsaVerifier(PublicConstant.PUBLIC_KEY));
        String claims = jwt.getClaims();
        Map map = JSONObject.parseObject(claims, Map.class);
        String openId = (String) map.get("openId");
        Long userId = (Long) map.get("userId");

        //判断refreshToken是否过期
        String refreshTokenKey = RedisConstant.USER_LOGIN_KEY_PREFIX + "refresh" + openId;
        String dataFromRedis = redisTemplate.opsForValue().get(refreshTokenKey);
        if (StringUtils.hasText(dataFromRedis)) {
            String jsonWebToken = getJsonWebToken(openId, userId);
            return getStringObjectHashMap(openId, jsonWebToken, refreshTokenKey);
        }
        //如果refreshToken过期,去登录
        throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
    }

    //获取用户信息
    @Override
    public UserInfoVo getUserInfo(Long userId) {
        UserInfo userInfo = userInfoMapper.selectById(userId);
        if (userInfo == null) {
            throw new GuiguException(201, "用户信息不存在");
        }
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, userInfoVo);
        return userInfoVo;
    }

    @Override
    public void updateUser(UserInfoVo userInfoVo) {
//        UserInfo userInfo = new UserInfo();
        Long userId = AuthContextHolder.getUserId();
        UserInfo userInfo = userInfoMapper.selectById(userId);
        if (userInfo == null) {
            throw new GuiguException(201, "用户信息不存在");
        }

        //判断是否修改图片
        String avatarUrl = userInfoVo.getAvatarUrl();
        if (StringUtils.hasText(avatarUrl)) {
            String userInfoAvatarUrl = userInfo.getAvatarUrl();
            if (StringUtils.hasText(userInfoAvatarUrl)) {
                String originalFilename = userInfoAvatarUrl.substring(userInfoAvatarUrl.lastIndexOf("/"), userInfoAvatarUrl.length());
                fileOpsServiceImpl.minioDeleteExample(originalFilename);
            }
        }

        userInfo.setAvatarUrl(userInfoVo.getAvatarUrl());
        userInfo.setNickname(userInfoVo.getNickname());
        userInfoMapper.updateById(userInfo);
    }

    @Override
    public Map<Long, String> getUserPaidAlbumTrackList(Long albumId, Long userId) {
        LambdaQueryWrapper<UserPaidTrack> queryWrapper = new LambdaQueryWrapper<UserPaidTrack>()
                .eq(UserPaidTrack::getAlbumId, albumId)
                .eq(UserPaidTrack::getUserId, userId);
        List<UserPaidTrack> userPaidTracks = userPaidTrackMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(userPaidTracks)) {
            new HashMap<>();
        }
        return userPaidTracks.stream().collect(Collectors.toMap(UserPaidTrack::getTrackId, v -> "1"));
    }

    @Override
    public Boolean getUserPaidAlbum(Long userId, Long albumId) {
        LambdaQueryWrapper<UserPaidAlbum> queryWrapper = new LambdaQueryWrapper<UserPaidAlbum>()
                .eq(UserPaidAlbum::getAlbumId, albumId)
                .eq(UserPaidAlbum::getUserId, userId);
        UserPaidAlbum userPaidAlbum = userPaidAlbumMapper.selectOne(queryWrapper);
        return userPaidAlbum != null;
    }

    @Override
    public Boolean collect(Long trackId) {
        Long userId = AuthContextHolder.getUserId();
        Criteria criteria = Criteria.where("userId").is(userId)
                .and("trackId").is(trackId);
        Query query = new Query(criteria);
        String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_COLLECT, userId);
        long count = mongoTemplate.count(query, UserCollect.class, collectionName);
        if (count == 0) {
            //收藏
            UserCollect userCollect = new UserCollect();
            userCollect.setId(ObjectId.get().toString());
            userCollect.setUserId(userId);
            userCollect.setTrackId(trackId);
            userCollect.setCreateTime(new Date());
            mongoTemplate.save(userCollect, collectionName);
            TrackStatMqVo trackStatMqVo = prepareCollectMsgDto(trackId, 1);
            rabbitService.sendMessage(MqConst.EXCHANGE_TRACK, MqConst.ROUTING_TRACK_STAT_UPDATE, JSONObject.toJSONString(trackStatMqVo));
            return true;
        } else {
            //取消收藏
            mongoTemplate.remove(query, collectionName);
            // 更新收藏量
            TrackStatMqVo trackStatMqVo = prepareCollectMsgDto(trackId, -1);
            rabbitService.sendMessage(MqConst.EXCHANGE_TRACK, MqConst.ROUTING_TRACK_STAT_UPDATE, JSONObject.toJSONString(trackStatMqVo));
            return false;
        }

    }

    @Override
    public Boolean isCollect(Long trackId) {
        Long userId = AuthContextHolder.getUserId();
        Criteria criteria = Criteria.where("userId").is(userId)
                .and("trackId").is(trackId);
        Query query = new Query(criteria);
        String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_COLLECT, userId);
        long count = mongoTemplate.count(query, UserCollect.class, collectionName);
        return count > 0;
    }

    @Override
    public IPage<UserCollectVo> findUserCollectPage(IPage<UserCollectVo> page, Long userId) {
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = new Query(criteria);
        int from = (int) ((page.getCurrent() - 1) * page.getSize());
        Sort sort = Sort.by(Sort.Direction.DESC, "updateTime");
        PageRequest pageRequest = PageRequest.of(from, (int) page.getSize(), sort);
        query.with(pageRequest);
        String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_COLLECT, userId);
        List<UserCollect> userCollectList = mongoTemplate.find(query, UserCollect.class, collectionName);

        List<Long> collectTrackIdList = userCollectList.stream().map(UserCollect::getTrackId).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(collectTrackIdList)) {
            Result<List<TrackListVo>> trackInfoVoResult = albumInfoFeignClient.getTrackInfoList(collectTrackIdList);
            List<TrackListVo> trackListVoList = trackInfoVoResult.getData();
            Assert.notNull(trackListVoList, "远程调用获取收藏列表失败");
            Map<Long, TrackListVo> map = trackListVoList.stream().collect(Collectors.toMap(TrackListVo::getTrackId, v -> v));

            List<UserCollectVo> userCollectVoList = userCollectList.stream().map(userCollect -> {
                UserCollectVo userCollectVo = new UserCollectVo();
                userCollectVo.setAlbumId(map.get(userCollect.getTrackId()).getAlbumId());
                userCollectVo.setTrackId(userCollect.getTrackId());
                userCollectVo.setCreateTime(new Date());
                userCollectVo.setTrackTitle(map.get(userCollect.getTrackId()).getTrackTitle());
                userCollectVo.setCoverUrl(map.get(userCollect.getTrackId()).getCoverUrl());
                return userCollectVo;
            }).collect(Collectors.toList());
            return page.setRecords(userCollectVoList);
        }
        return page;
    }

    @Override
    public Boolean isSubscribe(Long albumId) {
        Long userId = AuthContextHolder.getUserId();
        Criteria criteria = Criteria.where("userId").is(userId)
                .and("albumId").is(albumId);
        Query query = new Query(criteria);
        String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_SUBSCRIBE, userId);
        long count = mongoTemplate.count(query, UserSubscribe.class, collectionName);
        return count > 0;
    }

    @Override
    public VipServiceConfig getAllVipConfig(Long itemId) {
        return vipServiceConfigService.getById(itemId);
    }


    /**
     * 封装收藏消息
     *
     * @param trackId 音轨id
     * @return 音轨统计消息
     */
    private TrackStatMqVo prepareCollectMsgDto(Long trackId, Integer count) {
        TrackStatMqVo trackStatMqVo = new TrackStatMqVo();
        trackStatMqVo.setBusinessNo(UUID.randomUUID().toString().replaceAll("-", ""));
//        trackStatMqVo.setAlbumId(0L);
        trackStatMqVo.setTrackId(trackId);
        trackStatMqVo.setStatType(SystemConstant.TRACK_STAT_COLLECT);
        trackStatMqVo.setCount(count);
        return trackStatMqVo;
    }
}

